import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, message, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import { setRouteInfo } from '@api/networkConfig';
import { _ } from 'core-js';
import { IP_RE, IP_V6, IP_ADDRESS_MASK } from '@util/constants';
const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 14
  }
};
function EditModal(props) {
  const { form, modalType, netWorkTableData = [], visible } = props;
  const { getFieldDecorator, validateFields } = form;
  const [netWorkList, setNetworkList] = useState([]);
  useEffect(() => {
    let dict = { work: '工作口', mgmt: '管理口', scan0: '扫描口' };
    let list = netWorkTableData.map(r => {
      return {
        value: r.name,
        label: r.rawname + dict[r.name]
      };
    });
    setNetworkList(list);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  // 重制
  const onReset = () => {
    form.resetFields();
  };
  const onCancel = () => {
    onReset();
    props.onCancel();
  };
  const rebuildNetWorkList = () => {
    return netWorkList.filter(r => r.value === 'scan0');
  };
  const onOk = () => {
    return validateFields(async (err, values) => {
      if (!err) {
        try {
          const { data } = await setRouteInfo({
            ...values,
            mask: String(values.mask),
            version: modalType
          });
          if (
            _.get(data, 'data.status') === 'failed' &&
            _.get(data, 'data.message') === 'network route repetition'
          ) {
            message.error('路由重复');
            return;
          }
          message.success('新增成功');
          onReset();
          props.onOk(modalType);
        } catch (error) {
          message.error(_.get(error, 'error.response.data.error') || '新增失败');
          return;
        }
      }
    });
  };

  return (
    <>
      <Modal
        title={modalType === 'ipv4' ? '添加ipv4' : '添加ipv6'}
        {...props}
        onOk={onOk}
        onCancel={onCancel}
        maskClosable={false}
      >
        <Form labelAlign="left">
          <Form.Item {...formItemLayout} label="网络地址" colon={false}>
            {getFieldDecorator('to', {
              rules: [
                {
                  required: true,
                  message: '请输入网络地址'
                },
                {
                  pattern: modalType === 'ipv4' ? IP_RE : IP_V6,
                  message: `请输入合法的${modalType === 'ipv4' ? 'IPv4' : 'IPv6'}地址`
                }
              ],
              validateFirst: true
            })(<Input placeholder="请输入网络地址" />)}
          </Form.Item>
          {modalType === 'ipv4' ? (
            <Form.Item {...formItemLayout} label="子网掩码" colon={false}>
              {getFieldDecorator('mask', {
                rules: [
                  {
                    required: true,
                    message: '请输入子网掩码'
                  },
                  {
                    pattern: IP_ADDRESS_MASK,
                    message: '请输入合法的IPv4地址子网掩码'
                  }
                ],
                validateFirst: true
              })(<Input placeholder="请输入子网掩码" />)}
            </Form.Item>
          ) : (
            <Form.Item {...formItemLayout} label="前缀长度" colon={false}>
              {getFieldDecorator('mask', {
                rules: [
                  {
                    required: true,
                    message: '长度必须为1-128的整数'
                  }
                ],
                validateFirst: true
              })(
                <InputNumber
                  max={128}
                  min={1}
                  placeholder="请输入前缀长度"
                  style={{ width: '100%' }}
                />
              )}
            </Form.Item>
          )}
          <Form.Item {...formItemLayout} label="路由节点" colon={false}>
            {getFieldDecorator('via', {
              rules: [
                {
                  required: true,
                  message: '请输入路由节点'
                },
                {
                  pattern: modalType === 'ipv4' ? IP_RE : IP_V6,
                  message: `请输入合法的${modalType === 'ipv4' ? 'IPv4' : 'IPv6'}地址`
                }
              ]
            })(<Input placeholder="请输入路由节点" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="网口" colon={false}>
            {getFieldDecorator('dev', {
              rules: [
                {
                  required: true,
                  message: '请输入网口'
                }
              ]
            })(
              <Select defaultValue="lucy">
                {rebuildNetWorkList().map(item => (
                  <Select.Option value={item.value} key={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            )}
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
EditModal.propTypes = {
  visible: PropTypes.bool,
  onOk: PropTypes.func,
  modalType: PropTypes.string,
  onCancel: PropTypes.func,
  netWorkTableData: PropTypes.array,
  form: PropTypes
};
export default Form.create()(EditModal);
